<template>
  <div class="main">
    <a-form-model ref="formLogin" class="user-layout-login" :model="form" :rules="rules" id="formLogin">
      <div style="font-size: 1.714rem; margin-bottom: 20px">
        登录<span
          style="font-size: 14px; float: right; line-height: 56px"
        >没有账号？<router-link
          class="register"
          :to="{ name: 'register' }"
          style="margin-right: 10px"
        >立即注册</router-link
        ></span
        >
      </div>
      <a-form-model-item ref="mobile" prop="mobile">
        <a-input
          size="large"
          type="text"
          class="login_ipt"
          style="width: 316px; height: 47px"
          placeholder="输入手机号或用户名"
          v-model="form.mobile"
          @blur="
            () => {
              $refs.mobile.onFieldBlur()
            }
          "
        >
          <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input>
      </a-form-model-item>
      <a-form-model-item prop="pass">
        <a-input-password
          size="large"
          class="login_ipt"
          style="width: 316px; height: 47px"
          placeholder="输入密码"
          v-model="form.pass"
        >
          <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
        </a-input-password>
      </a-form-model-item>

      <a-form-model-item ref="code" prop="code">
        <div class="flex row_bet" style="width: 316px">
          <a-input
            size="large"
            type="text"
            class="login_ipt"
            style="width: 116px; height: 47px"
            placeholder="验证码"
            v-model="form.code"
            @blur="
              () => {
                $refs.code.onFieldBlur()
              }
            "
          >
            <a-icon slot="prefix" type="key" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
          <img :src="codeimg" alt="" srcset="" class="codeimg" @click="getcode" />
        </div>
      </a-form-model-item>

      <a-form-model-item style="margin-top: 24px">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="state.loading"
          :disabled="state.loginBtn"
          @click="handleSubmit"
        >登 录</a-button
        >
      </a-form-model-item>
      <div style="text-align: center;">
        <router-link :to="{ name: 'recover' }" class="forge-password">
          已有账号，忘记密码?</router-link
        >
      </div>
    </a-form-model>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { get2step } from '@/api/loginApi'

export default {
  data () {
    return {
      code_id: '',
      codeimg: '',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      // form: this.$form.createForm(this),
      form: {
        mobile: '',
        pass: '',
        code: ''
      },
      state: {
        time: 60,
        loading: false,
        loginBtn: true,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      },
      rules: {
        mobile: [
          {
            required: true,
            message: '请输入手机号或者用户名',
            trigger: 'blur'
          }
          // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' }
        ],
        pass: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 5,
            message: '请输入5位的验证码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    'form.mobile': function (val) {
      // console.log(val)
      if (this.form.pass !== '' && this.form.code !== '' && val !== '') {
        this.state.loginBtn = false
      } else {
        this.state.loginBtn = true
      }
    },
    'form.pass': function (val) {
      if (this.form.mobile !== '' && this.form.code !== '' && val !== '') {
        this.state.loginBtn = false
      } else {
        this.state.loginBtn = true
      }
    },
    'form.code': function (val) {
      if (this.form.mobile !== '' && this.form.pass !== '' && val !== '') {
        this.state.loginBtn = false
      } else {
        this.state.loginBtn = true
      }
    }
  },
  created () {
    this.getcode()
  },
  methods: {
    ...mapActions(['Login', 'Logout']),

    getcode () {
      get2step({})
        .then((res) => {
          console.log('验证码', res)
          // this.requiredTwoStepCaptcha = res.result.stepCode
          if (res.code === 200) {
            this.codeimg = res.data.pic
            this.code_id = res.data.key
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleSubmit () {
      this.$refs.formLogin.validate((valid) => {
        if (valid) {
          // console.log(this.form)
          this.form.code_id = this.code_id
          this.Login(this.form)
            .then((res) => this.loginSuccess(res))
            .catch((err) => this.requestFailed(err))
            .finally(() => {
              this.state.loginBtn = false
            })
        } else {
          setTimeout(() => {
            this.state.loginBtn = false
          }, 600)
          return false
        }
      })
    },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess (res) {
      // console.log('----', res)
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
          this.$router.push({ name: 'analysis' }, () => {
            console.log('onComplete')
            this.$notification.success({
              message: '欢迎',
              description: `${timeFix()}，欢迎回来`
            })
          })
          */
      this.$router.push({
        path: '/'
      })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed (err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .login_ipt::v-deep {
    .ant-input {
      border-radius: 6px;
      border: 1px solid #d9d9d996;
    }
    .ant-input-lg {
      height: 47px;
    }
  }

  .codeimg {
    width: 190px;
    height: 47px;
    border-radius: 10px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    width: 316px;
    height: 47px;
    padding: 0 15px;
    font-size: 20px;
    border-radius: 6px;
    border: 1px solid #d9d9d996;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
